import { mapGetters } from "vuex";

import { formulaRules } from "@/views/centralizedControl/deviceOperation/constant";
import {
  updateFormulaDownloadInfoZK,
  formulaEdit
} from "@/api/deviceOperation";
export const mixinFurnaceFormulaInfo = {
  data() {
    return {
      mixinIssuedShow: false,
      mixinIsIssued: false, //下发 还是 编辑阶段
      mixinFormulaParameter: [], //配方的参考数据
      formMixinStageTable: {
        tableData: []
      },
      mixinIssStageTable: [],
      mixinIssuedStageVisible: false,
      mixinRow: {}, //任务的当前行信息
      mixinStageVisible: false, //编辑配方的弹框
      mixinStageBtnloading: false
    };
  },
  computed: {
    ...mapGetters(["controlDeviceInfo", "taskDownLoadInfos"]),
    // 设备toekn
    deviceToken() {
      return this.controlDeviceInfo.token;
    },
    mixinRadioLable() {
      return function(item, downscope) {
        return (
          item.options.find(f => f.value == downscope.row[item.key])?.label ||
          "--"
        );
      };
    }
  },
  methods: {
    // 编辑阶段
    mixinSubmitInfo() {
      return new Promise((resolve, reject) => {
        updateFormulaDownloadInfoZK(
          this.formMixinStageTable.tableData.map((item, index) => {
            return {
              ...item,
              stageId: index + 1,
              token: "",
              formulaDownId: this.mixinRow.formulaDownid
            };
          })
        )
          .then(res => {
            resolve();
          })
          .catch(err => {
            this.stageBtnloading = false;
            reject(err);
          });
      });
    },
    // 阶段提交
    async mixinSubmitStage() {
      return new Promise(async (resolve, reject) => {
        try {
          // formulaDownload/updateZK/
          const res = await formulaEdit([this.mixinRow.id]);
          this.mixinStageBtnloading = false;
          const { data } = res;
          if (data) {
            this.$msg({
              type: "success",
              message: "下发成功"
            });
            resolve();
          } else {
            this.$msg("下发失败");
            reject();
          }
        } catch (error) {
          this.$msg("下发失败");
          this.mixinStageBtnloading = false;
          reject();
        }
      });
    },
    // 保存配方
    async mixinSubmit(stageTable) {
      console.log("object :>> ", this.formMixinStageTable.tableData);
      if (!this.formMixinStageTable.tableData.length) {
        this.$msg("请添加配方信息");
        return;
      }
      this.mixinStageBtnloading = true;
      await this.mixinSubmitInfo();
      // 下发
      await this.mixinSubmitStage();
      this.mixinStageBtnloading = false;
      this.mixinStageVisible = false;
      this.mixinIssuedStageVisible = false;
      await this.$store.dispatch(
        "centralizedControl/getTaskDownLoadInfos",
        this.deviceToken
      );
    },
    // 删除配方
    mixinDel(index) {
      this.formMixinStageTable.tableData.splice(index, 1);
    },
    // 添加配方
    mixinAddFormula(obj) {
      let form = {};
      if (obj) {
        form = obj;
      } else {
        this._formulaInfo.forEach(item => {
          if (!form[item.key]) {
            form[item.key] = item.defaultValue;
          }
        });
      }
      this.formMixinStageTable.tableData.push(form);
    },
    // 任务下发编辑阶段
    mixinEditStage(row, mixinIsIssued) {
      // 是否是 下发true 还是编辑false
      this.mixinIsIssued = mixinIsIssued;
      this.formMixinStageTable.tableData = _.sortBy(
        row.formulaDownloadZKInfo,
        "stageId"
      );
      this.mixinRow = _.cloneDeep(row);
      this.mixinStageVisible = true;
      // this.mixinIssuedStageVisible = true;

      const arr = _.cloneDeep(row.formulaParameter);
      // 取出表头
      this.mixinIssStageTable = [];
      this.formMixinStageTable = {
        tableData: []
      };
      arr[0].keys.forEach((key, keyIndex) => {
        this.mixinIssStageTable.push({
          label: key,
          key: key
        });
      });
      // 编辑的话 不用赋默认值
      if (!this.mixinIsIssued) {
        return;
      }
      this.$set(
        this.formMixinStageTable,
        "tableData",
        arr.map(item => {
          let obj = {};
          item.keys.forEach((key, keyIndex) => {
            obj[key] = item.values[keyIndex];
          });
          let oneExpandInfo = "";
          let twoExpandInfo = "";
          // 保温时间上下限一样直接赋值
          if (obj[formulaRules.UP_TIME] && obj[formulaRules.DOW_TIME]) {
            if (obj[formulaRules.UP_TIME] == obj[formulaRules.DOW_TIME]) {
              twoExpandInfo = obj[formulaRules.UP_TIME];
            }
          }

          // 加热时间一样的直接赋值
          if (
            obj[formulaRules.DOW_HEAT_TIME_ZK] &&
            obj[formulaRules.UP_HEAT_TIME_ZK]
          ) {
            if (
              obj[formulaRules.DOW_HEAT_TIME_ZK] ==
              obj[formulaRules.UP_HEAT_TIME_ZK]
            ) {
              twoExpandInfo = obj[formulaRules.DOW_HEAT_TIME_ZK];
            }
          }

          // 温度上下限一样 直接赋值
          if (obj[formulaRules.UP_TEMP] == obj[formulaRules.DOW_TEMP]) {
            oneExpandInfo = obj[formulaRules.UP_TEMP];
          }

          return {
            ...obj,
            // 设定温度
            oneExpandInfo: oneExpandInfo,
            // 设定时间
            twoExpandInfo: twoExpandInfo,
            threeExpandInfo: "",
            fourExpandInfo: "",
            fiveExpandInfo: "",
            sixExpandInfo: "",
            sevenExpandInfo: "",
            eightExpandInfo: "",
            nineExpandInfo: "",
            tenExpandInfo: ""
            // setTime:
            //   obj["保温时间上限"] == obj["保温时间下限"]
            //     ? obj["保温时间上限"]
            //     : "",
            // setTemp:
            //   obj["温度上限"] == obj["温度下限"] ? obj["温度上限"] : "",
            // volumeTemp: 10
          };
        })
      );
    },
    // 点击任务下发弹框并获取任务
    async mixinHandleIssued() {
      await this.$store.dispatch(
        "centralizedControl/getTaskDownLoadInfos",
        this.deviceToken
      );
      console.log("mixin中点击任务下发 :>> ", this.taskDownLoadInfos);
      this.mixinIssuedShow = true;
    }
  }
};
